import axios from 'axios';
import _ from 'lodash';
import defaultOptions from './default-options.js';
import handleRequestFulfilled from './handle-request-fulfilled.js';
import handleResponseFulfilled from './handle-response-fulfilled.js';
import handleResponseRejected from './handle-response-rejected.js';

/**
 * Axios构建器
 *
 * 使用方式
 * 1. 创建一个实例
 * 2. 调用实例的buildAxiosInstance方法
 *
 * 示例
 * let axiosBuilder = new AxiosBuilder({
 *     ...
 * });
 * axiosBuilder.buildAxiosInstance();
 */
class AxiosBuilder {
  constructor(options) {
    this.options = _.defaultsDeep(options, defaultOptions);
  }
  
  buildAxiosInstance() {
    // 创建axios实例
    const axiosInstance = axios.create({
      baseURL: this.options.baseUrl,
      timeout: this.options.timeout,
    });
    
    // 注册请求拦截器。将handleRequestFulfilled中的this绑定为AxiosBuilder的this
    axiosInstance.interceptors.request.use(handleRequestFulfilled.bind(this));
    
    // 注册响应拦截器。将handleResponseFulfilled和handleResponseRejected中的this绑定为AxiosBuilder的this
    axiosInstance.interceptors.response.use(
      handleResponseFulfilled.bind(this),
      handleResponseRejected.bind(this)
    );
    
    return axiosInstance;
  }
}

export default AxiosBuilder;